package com.xxc.hs.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.xxc.hs.bean.DataType;
import com.xxc.hs.bean.WaterDataInfo;

import java.util.ArrayList;
import java.util.List;

public class WaterDataHelper extends SQLiteOpenHelper {
    private static WaterDataHelper helper;
    private static final String DB_NAME = "water_data.db";
    private static final int VERSION = 1;
    private static final String TABLE_NAME = "water_data_table";

    // 列名常量
    private static final String COL_ID = "water_data_id";
    private static final String COL_WATER_LEVEL = "waterLevel_value";
    private static final String COL_PH = "ph_value";
    private static final String COL_TURBIDITY = "turbidity_value";
    private static final String COL_DISSOLVED = "dissolved_value";
    private static final String COL_YULV = "yuLv_value";
    private static final String COL_WATER_TEMP = "waterTemp";
    private static final String COL_TIME = "time";

    private WaterDataHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    public synchronized static WaterDataHelper getInstance(Context context) {
        if (helper == null) {
            helper = new WaterDataHelper(context.getApplicationContext());
        }
        return helper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
                COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_WATER_LEVEL + " TEXT, " +
                COL_PH + " TEXT, " +
                COL_TURBIDITY + " TEXT, " +
                COL_DISSOLVED + " TEXT, " +
                COL_YULV + " TEXT, " +
                COL_WATER_TEMP + " TEXT, " +
                COL_TIME + " TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    /**
     * 添加数据
     */
    public long InsertWaterData(WaterDataInfo dataInfo) {
        SQLiteDatabase db = getWritableDatabase();
        long id = -1;

        try (db) { // try-with-resources 自动关闭数据库
            ContentValues values = new ContentValues();
            values.put(COL_WATER_LEVEL, dataInfo.getWaterLevel());
            values.put(COL_PH, dataInfo.getPh());
            values.put(COL_TURBIDITY, dataInfo.getTurbidity());
            values.put(COL_DISSOLVED, dataInfo.getDissolved());
            values.put(COL_YULV, dataInfo.getYuLv());
            values.put(COL_WATER_TEMP, dataInfo.getWaterTemp());
            values.put(COL_TIME, dataInfo.getTime());

            id = db.insert(TABLE_NAME, null, values);
        } catch (Exception e) {
            e.printStackTrace(); // 考虑使用日志框架
        }
        return id;
    }


    /**
     * 根据类型和身份获取水质数据
     */
    @SuppressLint("Range")
    public List<WaterDataInfo> getWaterDataByType(int limit, DataType... dataTypes) {
        List<WaterDataInfo> dataInfoList = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = null;

        try {
            // 构建查询条件
            StringBuilder selection = new StringBuilder();
            List<String> selectionArgs = new ArrayList<>();

            if (dataTypes != null && dataTypes.length > 0) {
                for (int i = 0; i < dataTypes.length; i++) {
                    // 将DataType映射到数据库列名
                    String columnName = mapDataTypeToColumnName(dataTypes[i]);
                    if (columnName != null) {
                        selection.append(columnName).append(" IS NOT NULL AND ")
                                .append(columnName).append(" != ''");

                        if (i < dataTypes.length - 1) {
                            selection.append(" OR ");
                        }
                    }
                }
            }

            // 执行查询
            cursor = db.query(
                    TABLE_NAME,
                    null,
                    selection.length() > 0 ? selection.toString() : null,
                    selectionArgs.toArray(new String[0]),
                    null,
                    null,
                    COL_ID + " DESC", // 按ID降序（最新数据在前）
                    String.valueOf(limit)
            );

            // 解析结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    WaterDataInfo dataInfo = new WaterDataInfo();
                    dataInfo.setWater_id(cursor.getInt(cursor.getColumnIndex(COL_ID)));
                    dataInfo.setWaterLevel(cursor.getString(cursor.getColumnIndex(COL_WATER_LEVEL)));
                    dataInfo.setPh(cursor.getString(cursor.getColumnIndex(COL_PH)));
                    dataInfo.setTurbidity(cursor.getString(cursor.getColumnIndex(COL_TURBIDITY)));
                    dataInfo.setDissolved(cursor.getString(cursor.getColumnIndex(COL_DISSOLVED)));
                    dataInfo.setYuLv(cursor.getString(cursor.getColumnIndex(COL_YULV)));
                    dataInfo.setWaterTemp(cursor.getString(cursor.getColumnIndex(COL_WATER_TEMP)));
                    dataInfo.setTime(cursor.getString(cursor.getColumnIndex(COL_TIME)));
                    dataInfoList.add(dataInfo);
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace(); // 考虑使用日志框架
        } finally {
            // 确保资源关闭
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }

        return dataInfoList;
    }


    /**
     * 获取水位数据
     */
    public List<WaterDataInfo> getWaterLevelData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.WATERLEVEL);
        }
        return getWaterDataByType(20, DataType.WATERLEVEL);
    }


    /**
     * 获取PH数据
     */
    public List<WaterDataInfo> getPHData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.PH);
        }
        return getWaterDataByType(20, DataType.PH);
    }


    /**
     * 获取浊度数据
     */
    public List<WaterDataInfo> getTurbidityData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.TURBIDITY);
        }
        return getWaterDataByType(20, DataType.TURBIDITY);
    }


    /**
     * 获取溶氧量数据
     */
    public List<WaterDataInfo> getDissolvedData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.DISSOLVED);
        }
        return getWaterDataByType(20, DataType.DISSOLVED);
    }


    /**
     * 获取余氯数据
     */
    public List<WaterDataInfo> getYuLvData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.YULV);
        }
        return getWaterDataByType(20, DataType.YULV);
    }

    /**
     * 获取水温数据
     */
    public List<WaterDataInfo> getWaterTempData(int type) {
        if (type == 1) {
            return getWaterDataByType(40, DataType.WATERTEMP);
        }
        return getWaterDataByType(20, DataType.WATERTEMP);
    }

    /**
     * 将DataType枚举映射到数据库列名
     */
    private String mapDataTypeToColumnName(DataType dataType) {
        switch (dataType) {
            case WATERLEVEL:
                return COL_WATER_LEVEL;
            case PH:
                return COL_PH;
            case TURBIDITY:
                return COL_TURBIDITY;
            case DISSOLVED:
                return COL_DISSOLVED;
            case YULV:
                return COL_YULV;
            case WATERTEMP:
                return COL_WATER_TEMP;
            default:
                return null;
        }
    }

}